package com.biscuit.page.basicservice.design.login.strategy;

import com.alibaba.fastjson.JSON;
import com.biscuit.page.basicservice.api.model.request.authorization.AuthorizationAReq;
import com.biscuit.page.basicservice.design.login.LoginType;
import com.biscuit.page.basicservice.model.entities.mysql.SysUser;
import com.biscuit.page.basicservice.model.enums.LoginTypeEnum;
import com.biscuit.page.basicservice.model.enums.VerifyCodeWorkTypeEnum;
import com.biscuit.page.basicservice.persistence.dao.UserDao;
import com.biscuit.page.basicservice.service.CommonService;
import com.biscuit.page.basicservice.utils.BaseExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 邮箱/手机 验证码登录
 *
 * @author biscuit
 * @createTime 2024/5/22 13:53
 */
@Slf4j
@Component
@LoginType(type = LoginTypeEnum.VERIFY_CODE_LOGIN)
public class VerifyCodeLogin implements LoginMoreTypeInterface {

    @Resource
    private UserDao userDao;

    @Resource
    private CommonService commonService;

    @Override
    public SysUser login(AuthorizationAReq req) {
        log.info("AuthorizationService login for VerifyCodeLogin start，request -> {}", JSON.toJSONString(req));

        BaseExceptionUtil.throwException(StringUtils.isNotBlank(req.getVerifyCode()), "验证码为空");

        // 校验验证码
        this.commonService.checkVerifyCode(VerifyCodeWorkTypeEnum.REGISTER_VERIFY_CODE.getType(), req.getAccount(), req.getAccount());

        // 根据账号查询用户信息
        SysUser sysUser = this.userDao.getByAccount(req.getAccount());

        // 校验用户是否存在
        BaseExceptionUtil.throwException(Objects.nonNull(sysUser), "用户不存在");

        log.info("AuthorizationService login for VerifyCodeLogin end，response -> {}", JSON.toJSONString(sysUser));
        return sysUser;
    }

}
